import API from '@/api'
import Msg from '@/utils/msg'
import Http from '@/http'

function Qiniu() {

  this.config = {
    qiniuUploadTokenURL: API.get_qiniu_uptoken,
    upload_file_url: 'https://up.qbox.me',
    file_pre: "http://img.gongyide.com/"
  }

  this.upload = function (file, callback) {
    var that = this;
    Msg.showLoading('上传中')
    this.getQiniuToken(function (upload_token) {
      var upload_file_url = "https://up.qbox.me";
      that.uploadFile(file, upload_file_url, upload_token, function (res) {
        Msg.hideLoading();
        if(res.video_percent){
          callback && callback({video_percent:res.video_percent});
        }else{
          var file_url = that.config.file_pre + "/" + res.key;
          callback && callback(file_url);
        }
      });
    });
  }

  this.getQiniuToken = function (callback) {
    var that = this;
    Http.getModel(this.config.qiniuUploadTokenURL, {}).then(function (resp) {
      console.log("resp:", resp)
      var token = resp.data.uptoken;
      callback && callback.call(this, token, that.config.upload_file_url);
    })
  }
  this.getQiniuTokenSync = function (callback) {

    var that = this;
    var resp = Http.syncRequest(this.config.qiniuUploadTokenURL, {});
    console.log("sync resp:", resp)
    return {
      token: resp.data,
      upload_url: that.config.upload_file_url
    }

  }

  this.uploadFile = function (fileObj, upload_url, upload_token, callback) {
    console.log('fileObj111:',fileObj)
    if (fileObj) {
      var file_type = fileObj.type;
      var patten = /^image/;
      console.log('123',file_type.match(patten));
      var img_flag = file_type.match(patten);
      if (img_flag&&fileObj.size / 1024 > 1025) { //大于1M，进行压缩上传
        console.log()
        photoCompress(fileObj, {
          quality: 0.4
        }, function (base64Codes) {
          //console.log("压缩后：" + base.length / 1024 + " " + base);
          var bl = convertBase64UrlToBlob(base64Codes);
          //alert("yasuo..");
          doUpload(bl, upload_token, upload_url, callback);
        });
      } else {
        doUpload(fileObj, upload_token, upload_url, callback);
      }

      function doUpload(fileObj, upload_token, upload_url, callback) {
        var form = new FormData();
        form.append("file", fileObj);// 文件对象
        form.append("token", upload_token);
        var key = "file" + new Date().getTime() + Math.floor(Math.random() * 10 + 1) + Math.floor(Math.random() * 10 + 1);
        form.append("key", key);
        var xhr = new XMLHttpRequest();
        xhr.open("post", upload_url, true);
        xhr.onload = function () {
          console.log("onload")
          console.log(xhr.responseText);
          var json = JSON.parse(xhr.responseText);
          callback && callback(json);
        };
        xhr.onerror = function () {
          console.log("上传失败")
        };
        xhr.upload.onprogress = function (evt) {
          console.log("onprogress")
          if (evt.lengthComputable) {//
            var progress = Math.round(evt.loaded / evt.total * 100) + "%";
            console.log("progress:", progress);
            var file_type = fileObj.type;
            var patten = /^video/;
            console.log('123',file_type.match(patten));
            var video_flag = file_type.match(patten);
            if(video_flag){
              callback && callback({video_percent:progress});
            }
          }
        };
        xhr.upload.onloadstart = function () {//上传开始执行方法
          console.log("onloadstart")
        };
        xhr.send(form);
      }
      function photoCompress(file, w, objDiv) {
        var ready = new FileReader();
        /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
        ready.readAsDataURL(file);
        ready.onload = function () {
          var re = this.result;
          canvasDataURL(re, w, objDiv)
        }
      }
      function canvasDataURL(path, obj, callback) {
        var img = new Image();
        img.src = path;
        img.onload = function () {
          var that = this;
          // 默认按比例压缩
          var w = that.width,
            h = that.height,
            scale = w / h;
          w = obj.width || w;
          h = obj.height || (w / scale);
          var quality = 0.7;  // 默认图片质量为0.7
          //生成canvas
          var canvas = document.createElement('canvas');
          var ctx = canvas.getContext('2d');
          // 创建属性节点
          var anw = document.createAttribute("width");
          anw.nodeValue = w;
          var anh = document.createAttribute("height");
          anh.nodeValue = h;
          canvas.setAttributeNode(anw);
          canvas.setAttributeNode(anh);
          ctx.drawImage(that, 0, 0, w, h);
          // 图像质量
          if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
            quality = obj.quality;
          }
          // quality值越小，所绘制出的图像越模糊
          var base64 = canvas.toDataURL('image/jpeg', quality);
          // 回调函数返回base64的值
          callback(base64);
        }
      }
      /**
       * 将以base64的图片url数据转换为Blob
       * @param urlData
       *            用url方式表示的base64图片数据
       */
      function convertBase64UrlToBlob(urlData) {
        var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {type: mime});
      }
    } else {
      Toast("未选择文件");
    }
  }
}


export default Qiniu;
